// ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "stdarg.h"

//按元素大小顺序插入到链表中
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdint.h>
uint64_t g_delayQueueRunTime = 0;

uint64_t getRunTime(void)
{
	return g_delayQueueRunTime;
}
void runTimeHandle(void)
{
	g_delayQueueRunTime++;
}
typedef struct delayQueueNode_T
{
	int32_t m_cmd;
	int32_t m_value;
	uint64_t m_offsetTime;//剩余偏移时间
	struct delayQueueNode_T *next;
};


void insertNode(struct delayQueueNode_T **head_t, int32_t cmd, int32_t value, uint64_t delayTime)
{
	struct delayQueueNode_T *previous_t;
	struct delayQueueNode_T *current_t;
	struct delayQueueNode_T *newNode_t;

	current_t = *head_t;
	previous_t = NULL;

	while (current_t != NULL && current_t->m_offsetTime <= delayTime + getRunTime())
	{
		previous_t = current_t;		//previous_t记录current_t上一个节点的位置
		current_t = current_t->next;
	}
	newNode_t = (struct delayQueueNode_T *)malloc(sizeof(struct delayQueueNode_T));
	if (newNode_t == NULL)
	{
		printf("内存分配失败!");
		exit(1);
	}
	newNode_t->m_cmd = cmd;
	newNode_t->m_value = value;
	newNode_t->next = current_t;
	newNode_t->m_offsetTime = delayTime + getRunTime();

	if (previous_t == NULL)
	{
		*head_t = newNode_t;
	}
	else
	{
		previous_t->next = newNode_t;
	}
}

void print32_tNode(struct delayQueueNode_T *head_t)
{
	struct delayQueueNode_T *current_t;
	current_t = head_t;
	while (current_t != NULL)
	{
		printf("%d ", current_t->m_value);
		current_t = current_t->next;
	}
	printf("\n");
}

void deleteNode(struct delayQueueNode_T **head_t)
{
	struct delayQueueNode_T *previous_t;
	struct delayQueueNode_T *current_t;

	current_t = *head_t;
	previous_t = NULL;

	while (current_t != NULL && current_t->m_offsetTime >= getRunTime())
	{
		previous_t = current_t;
		current_t = current_t->next;
	}

	if (current_t == NULL)
	{
		return;
	}
	else
	{
		*head_t = current_t->next;
		free(current_t);
	}
}
int32_t main(void)
{
	struct delayQueueNode_T *head_t = NULL;

	insertNode(&head_t, 1,20,50);
	insertNode(&head_t, 1, 50, 350);
	insertNode(&head_t, 1, 60, 450);
	insertNode(&head_t, 1, 40, 250);
	insertNode(&head_t, 1, 70, 550);
	insertNode(&head_t,  1, 30, 150);
	insertNode(&head_t, 1, 10,20);
	print32_tNode(head_t);

	for (int32_t i = 0; i < 1; ++i)
	{
		runTimeHandle();
		deleteNode(&head_t);
	}
	
	print32_tNode(head_t);

	while (1)
		;

	return 0;
}